<template>
  <je-modal
    v-model:visible="visible"
    width="600px"
    :title="title"
    height="auto"
    :resize="false"
    :maximizable="false"
    cancel-button
    :ok-button="handleOk"
    @close="handleClose"
  >
    <je-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      autocomplete="off"
    >
      <je-form-item label="名称" name="TABLECOLUMN_NAME">
        <je-input v-model:value="formState.TABLECOLUMN_NAME" @change="handleChangeName" />
      </je-form-item>

      <je-form-item label="编码" name="TABLECOLUMN_CODE">
        <je-input v-model:value="formState.TABLECOLUMN_CODE" />
      </je-form-item>
      <je-form-item label="类型" name="TABLECOLUMN_TYPE">
        <je-select v-model:value="formState.TABLECOLUMN_TYPE" allow-clear>
          <je-select-option
            v-for="(item, index) in arrFiledType"
            :key="index"
            :value="item.code"
            :disabled="item.disabled"
          >
            {{ item.text }}
          </je-select-option>
        </je-select>
      </je-form-item>
      <je-form-item label="长度|自定义" name="TABLECOLUMN_LENGTH">
        <je-input-number
          v-model:value="formState.TABLECOLUMN_LENGTH"
          :min="0"
          :parser="(value) => value.replace(/[^0-9]+/g, '')"
          style="width: 100%"
        />
      </je-form-item>
    </je-form>
  </je-modal>
</template>

<script>
  import { ref, toRefs, reactive, defineComponent, watch } from 'vue';
  import { Modal, Form, Input, InputNumber, Select } from '@jecloud/ui';
  import { pinyin } from '@jecloud/utils';

  import { ListFieldConfigAddNormal } from '@/api/index';

  import { FIELDTYPE } from '@/helper/constant';
  import { useFuncStore } from '@/store/func-store';

  export default defineComponent({
    name: 'AddNormalField',
    components: {
      JeModal: Modal,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeInput: Input,
      JeInputNumber: InputNumber,
      JeSelect: Select,
      JeSelectOption: Select.Option,
    },
    props: {
      visble: {
        type: Boolean,
        default: false,
      },
      recordData: {
        type: Object,
        default: () => {},
      },
    },
    emits: ['changeModal'],
    setup(props, { emit }) {
      const funcStore = useFuncStore();
      const state = reactive({
        visible: props.visble,
        title: '普通字段',
        formRef: ref(),
        formState: {},
        arrFiledType: FIELDTYPE,
        labelCol: {
          style: { width: '120px', margin: '0 2px 0 0' },
        },
        wrapperCol: {
          style: { margin: '0 35px 0 0' },
        },
        rules: {
          TABLECOLUMN_NAME: [
            { required: true, message: '请输入名称' },
            { max: 40, message: '不能大于40个字符' },
            { pattern: '^[^\\\\/*?:"\'<>|\x22]+$', message: '不能输入非法字符' },
          ],
          // TABLECOLUMN_CODE: [
          //   { required: true, message: '请输入编码' },
          //   { max: 40, message: '不能大于40个字符' },
          //   {
          //     pattern: '^[A-Z]{1}[A-Z_0-9]{0,100}$',
          //     message: '编码由大写字母、下划线、数字组成,且首位为大写字母',
          //   },
          // ],
          TABLECOLUMN_TYPE: [{ required: true, message: '请选择类型' }],
        },
      });
      watch(
        () => funcStore.funcBean.RESOURCETABLE_IMPORT,
        (val) => {
          if (val == '1') {
            state.rules.TABLECOLUMN_CODE = [
              { required: true, message: '请输入编码' },
              { max: 40, message: '不能大于40个字符' },
            ];
          } else {
            state.rules.TABLECOLUMN_CODE = [
              { required: true, message: '请输入编码' },
              { max: 40, message: '不能大于40个字符' },
              {
                pattern: '^[A-Z]{1}[A-Z_0-9]{0,100}$',
                message: '编码由大写字母、下划线、数字组成,且首位为大写字母',
              },
            ];
          }
        },
        { deep: true, immediate: true },
      );
      const methods = {
        handleClose() {
          state.visible = false;
          emit('changeModal', { visible: false });
        },

        handleOk({ button }) {
          state.formRef
            .validate()
            .then(() => {
              methods.handleSave(button);
            })
            .catch((error) => {
              console.error(error);
            });
          return false;
        },

        handleSave(btn) {
          btn.loading = true;
          const params = {
            tableCode: 'JE_CORE_TABLECOLUMN',
            FUNCINFO_ID: props.recordData.JE_CORE_FUNCINFO_ID,
            TABLECOLUMN_NAME: state.formState.TABLECOLUMN_NAME,
            TABLECOLUMN_CODE: state.formState.TABLECOLUMN_CODE,
            TABLECOLUMN_TYPE: state.formState.TABLECOLUMN_TYPE,
            TABLECOLUMN_LENGTH: state.formState.TABLECOLUMN_LENGTH,
            TABLECOLUMN_TABLECODE: props.recordData.FUNCINFO_TABLENAME,
          };
          ListFieldConfigAddNormal(params, {
            pd: funcStore.product.code,
          })
            .then((res) => {
              Modal.message(res.message, 'success');

              state.visible = false;
              emit('changeModal', { type: 'refreshData', visible: false });

              btn.loading = false;
            })
            .catch((error) => {
              Modal.alert(error.message, 'error');
              btn.loading = false;
            });
        },

        handleChangeName() {
          const arr = props.recordData.FUNCINFO_TABLENAME.split('_');
          const str = arr[arr.length - 1];
          state.formState.TABLECOLUMN_CODE =
            str + '_' + pinyin(state.formState.TABLECOLUMN_NAME, 'PY');
        },
      };

      return {
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style lang="less" scoped></style>
